package com.nageoffer.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;
import lombok.extern.slf4j.Slf4j;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密工具类
 */
@Slf4j
public class DruidEncryptUtil {
    /**
     * 公钥
     */
    private static String publicKey;

    /**
     * 私钥
     */
    private static String privateKey;

    static {
        try {
            String[] keyPairs = ConfigTools.genKeyPair(512);
            privateKey = keyPairs[0];
            log.info("privateKey: " + privateKey);
            publicKey = keyPairs[1];
            log.info("publicKey: " + publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 私钥加密
     */
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        log.info("encrypt: " + encrypt);
        return encrypt;
    }

    /**
     * 公钥解密
     */
    public static String decrypt(String encrypt) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey,encrypt);
        log.info("decrypt: " + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("123456");
        log.info("encrypt-123456: " + encrypt);
    }
}
